/** Старт инициализации */
$(document).ready(function() {

	$('#cookiesHackForm').submit();

	ROUTER = new VKPlayer.AppRouter;

	AppView = new VKPlayer.Views.App;

	AppView.bind('inited', function() {
		ROUTER.navigate('popular/', true)
	});

	Backbone.history.start();

	//VK._apiId = 2457999;
	VK.init(function() {
		viewer_id = $('body').data('viewer_id');
		if (!viewer_id)
			return;

		DEQUE = new VKPlayer.Models.Deque();

		getProfiles(viewer_id)
			.done(function(result) {
				if (result) {
					USER = new VKPlayer.Models.User(_.first(result));
					VKPlayer.loadTracklist();
					USER.loadFriends();
					DEQUE.rotateUserFriends(viewer_id);
					AppView.setInit('user');
				}
			});


		$(VKPlayer.Selectors.jPlayerId).jPlayer({
			ready: function() {
				PLAYER = new VKPlayer.Models.Player;
				AppView.setInit('player');
			},
			repeat: function(event) {

				$(this).unbind(".jPlayerRepeat").bind($.jPlayer.event.ended + ".jPlayer.jPlayerRepeat", function() {
					if (event.jPlayer.options.loop) {
						PLAYER.trigger('play', {scrobblingDisabled: true })
					} else {
						PLAYER.trigger('play_next')
					}
				});

				if (PLAYER)
					PLAYER.trigger('loopChange', {loop: event.jPlayer.options.loop})

			},
			pause: function(event) {
				PLAYER.trigger('pause')
			},
			play: function(event) {
				PLAYER.trigger('resume')
				PLAYER.trigger('play.first_load')
				PLAYER.trigger('volumeChange')
			},
			timeupdate: function(event) {
				var currentTime = event.jPlayer.status.currentTime;
				PLAYER.trigger('timeSync', {currentTime:currentTime});
			},
			loadstart: function() {
			},
			progress: function() {
				downloadingOn();
			},
			ended: function() {
			},
			volumechange: function(event) {
				var muted = event.jPlayer.options.muted;
				PLAYER.trigger('volumeChange', {muted:muted})
			},

			swfPath: "/js/jplayer/Jplayer.swf",
			supplied: "mp3",
			solution: "flash, html"
		});

	});

	/**
	 * Детские штучки
	 */
	if (Modernizr && !Modernizr.input.placeholder) {
		$('input[placeholder],textarea[placeholder]').each(function() {
			var input = this;
			var $input = $(input);
			var placeholder = $input.attr('placeholder');
			if (!placeholder) return;
			if ($input.val() == '' || $input.val() == placeholder) {
				$input.addClass('input-placeholder').val(placeholder);
			}
			$input.bind('focus keydown', function() {
				if ($input.hasClass('input-placeholder')) {
					$input.val('').removeClass('input-placeholder')
				}
			});
			$input.bind('blur', function() {
				if ($input.val() == '') {
					$input.addClass('input-placeholder').val(placeholder);
				} else {
					$input.removeClass('input-placeholder')
				}
			});
			if (input.form) {
				$(input.form).bind('submit', function() {
					if ($input.hasClass('input-placeholder')) {
						$input.val('').removeClass('input-placeholder')
					}
				})
			}
		});
	}

	$('body')
		.delegate('.hash-trigger', 'click', function() {
			var $this = $(this);
			if ($this.closest('.menu-item').is('.active') || $this.closest('.menu-item').is('.inactive'))
				return true;

			$this.closest('.menu').find('.menu-item').removeClass('active');
			$this.closest('.menu-item').addClass('active');

			var trigger = $this.data('hash');
			if (trigger)
				ROUTER.navigate(trigger, true);
		});

	$('.menu').delegate('.folder .folder-control', 'click', function() {
		var $this = $(this);
		var $folder = $this.closest('.folder');
		var $content = $folder.find('.content').first();

		if ($folder.is('.anchor') &&
			$folder.is('.stay-open') &&
			$folder.is('.opened') &&
			!$folder.is('.active'))
			return true;

		if ($folder.is('.opened')) {
			$content.slideUp(100, function() {
				resizeFrame();
			});
			$folder.removeClass('opened');
		} else {
			var trigger = $this.data('hash');
			if (trigger)
				ROUTER.navigate(trigger, true);
			$content.slideDown(100, function() {
				resizeFrame();
			});
			$folder.addClass('opened');
		}
	})

	var searchTimeoutId;
	$('#search-input').bind('keyup', function() {
		var $input = $(this);
        var $content = $(VKPlayer.Selectors.content);
		
		if (searchTimeoutId)
			window.clearTimeout(searchTimeoutId);

		searchTimeoutId = window.setTimeout(function() {
            $content.addClass('loading');
			var query = $input.val();
			searchAudio({q: query, count: 200, auto_complete: 0})
				.done(function(data) {
					$content.removeClass('loading')
					.clear()
					.appendTitle({title: 'Результаты поиска'})
					.appendTitle({sub_title: 'Запрос: '+query});
					if (!_.isEmpty(data.list)) {
						PLAYER.trigger('hide');
						ROUTER.flashAnchor('');
						var tracks = new VKPlayer.Collections.Tracks(data.list);
						tracklist = new VKPlayer.Models.Tracklist();
						tracklist.linkTracks(tracks);
						tracklist.trigger('show');
					}
				});
		}, 777)
	});

});
